package com.lilicould.filter;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter("/page/*")
public class PageFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取请求和响应对象，转换为HttpServletRequest和HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(false);
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        if (session == null || session.getAttribute("userNo") == null || session.getAttribute("role") == null) {
            // 用户未登录，跳转到登录页面
            request.getRequestDispatcher("/page/login.jsp").forward(request, response);
            return; // 添加return以防止继续执行
        }

        // 用户已登录，进行身份验证，防止访问其他页面
        if ("student".equals(session.getAttribute("role"))) {
            if (uri.startsWith(contextPath + "/page/student")) {
                filterChain.doFilter(request, response);
            } else {
                request.getRequestDispatcher("/page/student/index.jsp").forward(request, response);
            }
        } else if ("teacher".equals(session.getAttribute("role"))) {
            if (uri.startsWith(contextPath + "/page/teacher")) {
                filterChain.doFilter(request, response);
            } else {
                request.getRequestDispatcher("/page/teacher/index.jsp").forward(request, response);
            }
        } else if ("admin".equals(session.getAttribute("role"))) {
            if (uri.startsWith(contextPath + "/page/admin")) {
                filterChain.doFilter(request, response);
            } else {
                request.getRequestDispatcher("/page/admin/index.jsp").forward(request, response);
            }
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
